package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryParam;
import com.tanhua.domain.vo.RecommendUserVo;
import com.tanhua.dubbo.api.db.QuestionApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class RecommendService {

    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity queryTodayBest() {
//        1、查询mongo的服务 返回 RecommendUser
        RecommendUser recommendUser =  recommendUserApi.queryTodayBest(UserHolder.getUserId());

        if(recommendUser==null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L);
            recommendUser.setScore(RandomUtils.nextDouble(95,99));
        }

//        2、根据 RecommendUser中的UserId 查询UserInfo
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
//        3、RecommendUser+UserInfo--->RecommendUserVo
        RecommendUserVo recommendUserVo = new RecommendUserVo();

        BeanUtils.copyProperties(userInfo,recommendUserVo);
         //"单身,本科,年龄相仿"
        if(StringUtils.isNotBlank(userInfo.getTags())){
            recommendUserVo.setTags( userInfo.getTags().split(","));
        }
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        return ResponseEntity.ok(recommendUserVo);

    }

    public ResponseEntity queryRecommendation(RecommendUserQueryParam param) {
//        从mongo  RecommendUser
//        10个RecommendUser
//            counts总记录数
//          PageResult-- List<RecommendUser> items;
        PageResult pageResult =  recommendUserApi.queryRecommendation(UserHolder.getUserId(),param.getPage(),param.getPagesize());
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();
        //判断recommendUserList是否为空  如果为空放一些模拟数据
        if(CollectionUtils.isEmpty(recommendUserList)){
//            放一些模拟数据
            for (int i = 0; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(RandomUtils.nextLong(1,99));
                recommendUser.setScore(RandomUtils.nextDouble(60,90));
                recommendUserList.add(recommendUser);
            }

//            把集合根据score排序 降序
//            recommendUserList.sort(new Comparator<RecommendUser>() {
//                @Override
//                public int compare(RecommendUser o1, RecommendUser o2) {
//                    return o2.getScore().intValue()-o1.getScore().intValue();
//                }
//            });

            recommendUserList.sort((o1,o2)->{
                return o2.getScore().intValue()-o1.getScore().intValue();
            });


        }

        List<RecommendUserVo> list = new ArrayList<>();
//        从mysql  UserInfo
        for (RecommendUser recommendUser : recommendUserList) {
            RecommendUserVo recommendUserVo = new RecommendUserVo();
//            recommendUser+UserInfo
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            BeanUtils.copyProperties(userInfo,recommendUserVo);
            if(StringUtils.isNotBlank(userInfo.getTags())){
                recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());

            list.add(recommendUserVo);
        }


        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);

    }

    public ResponseEntity queryPersonalInfo(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);

        RecommendUserVo recommendUserVo = new RecommendUserVo();
//            recommendUser+UserInfo
        BeanUtils.copyProperties(userInfo,recommendUserVo);
        if(StringUtils.isNotBlank(userInfo.getTags())){
            recommendUserVo.setTags(userInfo.getTags().split(","));
        }


        //两个人的缘分值    UserHolder.getUserId()  userId
        Long toUserId = UserHolder.getUserId();
//        查询两个人的缘分值
        Long  fateValue = recommendUserApi.queryScore(toUserId ,userId);
        recommendUserVo.setFateValue(fateValue);

        return ResponseEntity.ok(recommendUserVo);
    }



    public ResponseEntity queryStrangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return ResponseEntity.ok(question==null?"可以交流一下吗？": question.getTxt());

    }

    public ResponseEntity replyStrangerQuestions(Long userId, String reply) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", UserHolder.getUserId().toString());  //发送方的id
        UserInfo userInfo = userInfoApi.findById( UserHolder.getUserId());
        map.put("nickname",userInfo.getNickname());

        Question question = questionApi.findByUserId(userId);
        map.put("strangerQuestion", question==null?"可以交流一下吗？": question.getTxt());
        map.put("reply",reply );
        String msg = JSON.toJSONString(map);
        huanXinTemplate.sendMsg(userId.toString(),msg);  // 2 发给142

        return ResponseEntity.ok(null);
    }

    public ResponseEntity cards(int num) {
        PageResult pageResult = recommendUserApi.queryRecommendation(UserHolder.getUserId(), 1, num);
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();
        List<RecommendUserVo> list = new ArrayList<>();
//        从mysql  UserInfo
        for (RecommendUser recommendUser : recommendUserList) {
            RecommendUserVo recommendUserVo = new RecommendUserVo();
//            recommendUser+UserInfo
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            BeanUtils.copyProperties(userInfo,recommendUserVo);
            if(StringUtils.isNotBlank(userInfo.getTags())){
                recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            list.add(recommendUserVo);
        }
        return ResponseEntity.ok(list);
    }


    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;

    public ResponseEntity love(Long likeUserId) {

//        1号用户右滑  11号

        Long userId = UserHolder.getUserId();
//        1、将喜欢记录插入到user_like表中
        userLikeApi.save(userId,likeUserId);
//        2、判断对方是否喜欢自己（登录人）
        boolean ifLike =  userLikeApi.ifLike(likeUserId,userId);
        if(ifLike){  //2.1 如果喜欢 向friend表插入两条数据 还需要将两人关系记录到环信上
            friendApi.save(userId,likeUserId);
            //        TODO 两个人成为好友需要记录到环信上
        }
        //        3、删除当前推荐的这一条数据
        recommendUserApi.delete(userId,likeUserId);
        return ResponseEntity.ok(null);

    }

    public ResponseEntity unlove(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        recommendUserApi.delete(userId,likeUserId);
        return ResponseEntity.ok(null);
    }
//



}
